#!/bin/bash
set -x
serviceName=proto
nameSpaces=$2
deployEnv=$3
urlPath=$4
echo "11-${urlPath}"
domainName=$5
echo "22-${domainName}"
Yml_path=$6
echo "33-${Yml_path}"

echo "44-${IMAGE_Name}"

if [ ! $# == 6 ]; then

  echo "Usage: $0 serviceName nameSpaces deployEnv urlPath domainName Yml_path"

  exit

fi


cert_manager=''

#自签证书
if [[ "$(echo $domainName|grep "fjfuyu")" != "" ]]
then
  cert_manager="1"
  if [[ "$(echo $nameSpaces|grep "dev")" != "" ]]
  then
    domainName="pm.platform.fjfuyu.net"
  elif [[ "$(echo $nameSpaces|grep "pre")" != "" ]]
  then
    domainName="stag."$domainName
  else
    domainName="prod."$domainName
  fi  
elif [[ "$(echo $domainName|grep "xueerqin")" != "" ]]
then
  cert_manager="1"
  if [[ "$(echo $nameSpaces|grep "dev")" != "" ]]
  then
    domainName="t-"$domainName
  elif [[ "$(echo $nameSpaces|grep "pre")" != "" ]]
  then
    domainName="s-"$domainName
  else
    domainName="p-"$domainName
  fi
else
  echo "域名：${domainName} 没有配置"
  exit 1
fi

#ssl证书泛域名
result=${domainName#*.}
SSL_secret="*."${result}
SSL_secretName=${result//./-}


echo "Ingress 域名是：$domainName"
echo "Ingress SSL证书泛域名： ${SSL_secret}"


mkdir -p "${Yml_path}"
cd ${Yml_path}

cat >${serviceName}-${deployEnv}-ingress-kong.yaml<<EOF
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ${serviceName}-tls
  namespace: ${nameSpaces}
  annotations:
EOF

if [[ "${cert_manager}" == "1" ]];then
cat >>${serviceName}-${deployEnv}-ingress-kong.yaml<<EOF
    cert-manager.io/cluster-issuer: letsencrypt-fjfuyu
EOF
fi

cat >>${serviceName}-${deployEnv}-ingress-kong.yaml<<EOF
    konghq.com/override: https-only
    kubernetes.io/ingress.class: "kong"
spec:
  tls:
  - secretName: ${SSL_secretName}
    hosts:
    - "${SSL_secret}"
  rules:
  - host: ${domainName}
    http:
      paths: 
      - path: /
        backend:
          serviceName: ${projectName}
          servicePort: 80
EOF
